﻿using System;
using Mbs.ComponentModel.Container.Context;

namespace Mbs.ComponentModel.Container.Lifestyle
{
    [Serializable]
    public class SingletontLifestyleManager : LifestyleManagerAdapter
    {
        private volatile Object instance;

       
        public override object Get(ICreateContext ctx)
        {
            if (instance == null)
            {
                lock (Activator)
                {
                    if (instance == null)
                    {
                        instance = base.Get(ctx);
                    }
                }
            }

            return instance;
        }

        public override bool Release(object instance)
        {
            return false;
        }

        public override bool Release()
        {
            if (instance != null)
            {
                if (OnDestroyed != null)
                    OnDestroyed(Info, instance);
                var dis = instance as IDisposable;
                if (dis != null)
                    dis.Dispose();
                instance = null;
            }
            return true;
        }

        protected override void Dispose(bool disposing)
        {
            if (instance != null) base.Release(instance);
        }
    }

    
}
